var app = {
    init:function(){
        this.param = {
            chinaName:"",
            province:"",
            city:"",
            county:""
        };
        this.time = "";
        this.target = null;
        this.points = [];
        this.getStationList(this.param);
        this.initForm();
        this.bindEvent();
        this.initMap();
    },
    initForm:function(){
        var that = this;
        layui.use('form', function(){
            var form = layui.form;
            var provinces = common.getProvinces();
            $("[name=province]").empty().append(template("select-option",{list:provinces}));
            form.render('select'); //刷新select选择框渲染
            form.on('select(province)', function(data){
                that.param.province = data.value;
                var cities = common.getCities(data.value);
                $("[name=city]").empty().append(template("select-option",{list:cities}));
                form.render('select'); //刷新select选择框渲染
              }); 
            form.on('select(city)', function(data){
                that.param.city = data.value;
                var zones = common.getZone(that.param.province,that.param.city);
                $("[name=zone]").empty().append(template("select-option",{list:zones}));
                form.render('select'); //刷新select选择框渲染
            }); 
            form.on('select(zone)', function(data){
                that.param.county = data.value;
            }); 
          });
    },
    bindEvent:function(){
        var that = this;
        $(document).on("click",".search",function(e){
            that.param.chinaName = $(".station-name").val();
            that.getStationList(that.param);
            e.preventDefault();
            e.stopPropagation();
        })
        $(document).on("click",".filter",function(e){
            that.getDetail(that.target,that.time);
            e.preventDefault();
            e.stopPropagation();
        })
        $(document).on("click",".export",function(e){
            // layer.confirm('您会导出' + that.total  +'条记录，需要等待较长时间，是否确定导出？', {
            //     btn: ['确定','取消'] //按钮
            //   }, function(){
            //     that.exportExcel();
            //   }, function(){
                
            //   });
            that.exportExcel();
            e.preventDefault();
            e.stopPropagation();
        })
    },
    exportExcel:function(){
        var that = this;
        that.loading = layer.load(0, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
        $.ajax({
            url:'/api/v1/meteorology/record/exportRecordods',
            type:'post',
            data:this.detailParam,
            success:function(res){
                layer.close(that.loading);
                if(res.errcode == "0000"){
                    layer.msg("导出成功",{icon: 1});
                    window.open(res.data.exportPath); 
                }else{
                    layer.msg(res.errmsg,{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    initMap:function(){
        var map = new BMap.Map("container",{mapType:BMAP_HYBRID_MAP,minZoom:5,maxZoom:8});
        // 创建地图实例  
        var point = new BMap.Point(116.404, 39.915);
        // 创建点坐标  
        map.centerAndZoom(new BMap.Point(105.000, 38.000), 6);
        //map.centerAndZoom(point, 15);
        // 初始化地图，设置中心点坐标和地图级别
        map.enableScrollWheelZoom(true);
        this.map = map;
    },
    addPoints:function(paramPoints){
        var that = this;
        if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
            this.map.clearOverlays();
            var points = [];  // 添加海量点数据
            for (var i = 0; i < paramPoints.length; i++) {
              points.push(new BMap.Point(parseFloat(paramPoints[i].longitude,10), parseFloat(paramPoints[i].latitude,10)));
              paramPoints[i].compareLongitude = parseFloat(paramPoints[i].longitude,10);
              paramPoints[i].compareLatitude = parseFloat(paramPoints[i].latitude,10)
            }
            that.points = paramPoints;
            var options = {
                size: BMAP_POINT_SIZE_NORMAL,
                shape: BMAP_POINT_SHAPE_STAR,
                color: '#f51b1b'
            }
            //console.log(points)
            var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
            pointCollection.addEventListener('click', function (e) {
              //alert('单击点的坐标为：' + e.point.lng + ',' + e.point.lat);  // 监听点击事件
              that.filterPoints(e.point);
            });
            // 鼠标经过时
            pointCollection.addEventListener("mouseover", function(e) {   
                var opts = {
                    position : e.point,    // 指定文本标注所在的地理位置
                    offset   : new BMap.Size(10, -10)    //设置文本偏移量
                }
                var zone = that.filterPoint(e.point);
                if(that.label){
                    that.map.removeOverlay(that.label);
                }
                that.label = new BMap.Label("地区名:"+ zone.county + ",灾害累计发生次数:" + "<span style='color:red'>" + zone.num + "</span>次", opts);  // 创建文本标注对象
                that.label.setStyle({
                    color:"#000",
                    fontSize:"16px;",
                    padding:"8px",
                    borderRadius:"5px",
                    borderColor:"#998dd5"
                });
                that.map.addOverlay(that.label);   
            });
            // 鼠标离开时
            pointCollection.addEventListener("mouseout", function(e) {
                that.map.removeOverlay(that.label);
            });
            this.map.addOverlay(pointCollection);  // 添加Overlay
        } else {
            alert('请在chrome、safari、IE8+以上浏览器查看本示例');
        }
    },
    filterPoint:function(point){
        var target = null;
        var that = this;
        for(var i = 0;i<this.points.length;i++){
            if(point.lng == this.points[i].compareLongitude && point.lat == this.points[i].compareLatitude){
                target = this.points[i];
                break;
            }
        }
        if(target){
            return target;
        }
    },
    filterPoints:function(point){
        var target = null;
        var that = this;
        for(var i = 0;i<this.points.length;i++){
            if(point.lng == this.points[i].compareLongitude && point.lat == this.points[i].compareLatitude){
                target = this.points[i];
                break;
            }
        }
        if(target){
            that.target = target;
            that.layerIndex = layer.open({
                type: 1,
                title: target.county + "&nbsp;灾害频次统计",
                closeBtn: 1,
                shadeClose:false,
                content: template("dialog-wrap",{}),
                btn: ['关闭'],
                area: ['600px', '500px']
                ,yes: function(index, layero){
                  //按钮【按钮一】的回调
                  layer.closeAll();
                },
                success:function(){
                    that.param.y3 = "";
                    layui.use('form', function(){
                        var form = layui.form;
                        form.render('select'); //刷新select选择框渲染
                        form.on('select(dynasty)', function(data){
                            that.param.y3 = data.value;
                        }); 
                      });
                    that.getDetail(target,that.time);
                    layui.use('laydate', function(){
                        var laydate = layui.laydate;
                        //执行一个laydate实例
                        laydate.render({
                            elem: '#year', //指定元素,
                            type:"year",
                            min:"100-1-1",
                            max:"1949-12-31",
                            value:"1949 - 1949",
                            isInitValue:false,
                            range:true,
                            done: function(value, date){
                                that.time = value;
                                that.getDetail(target,value);
                            }
                        });
                    });
                }
            });
        }else{
            console.log("未匹配到台站");
        }
    },
    // initBar:function(data){
    //     var list1 = [];
    //     var list2 = [];
    //     if(data){
    //         for(var i = 0; i < data.length; i++){
    //             list1.push(data[i].classname);
    //             list2.push(data[i].num);
    //         }
    //     }
        
    //     option = {
    //         xAxis: {
    //             type: 'category',
    //             data: list1
    //         },
    //         axisLabel: {
    //             formatter: '{value}次'
    //         },
    //         tooltip : {
    //             trigger: 'axis',
    //             axisPointer : {            // 坐标轴指示器，坐标轴触发有效
    //                 type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
    //             }
    //         },
    //         yAxis: {
    //             type: 'value'
    //         },
    //         series: [{
    //             data: list2,
    //             type: 'bar',
    //             itemStyle : {
    //                 normal : {
    //                     color:'#998dd5'
    //                 }
    //             }
    //         }]
    //     };
    //     var chart = echarts.init(document.getElementById('disaster'))
    //     chart.setOption(option);        
    // },
    getDetail:function(point,value){
        var that = this;
        var param = {};
        if(value == ""){
            param.startY1 = "";
            param.endY1 = "";
        }else{
            param.startY1 = value.split(" - ")[0];
            param.endY1 = value.split(" - ")[1];
        }
        that.param.startY1 = param.startY1;
        that.param.endY1 = param.endY1;
        param.l2 = point.province
        param.l3 = point.county;
        param.y3 = that.param.y3;
        //param.y3 = $("#dynasty").val();
        that.detailParam = param;
        $.ajax({
            url:'/api/v1/meteorology/record/getRecordods',
            type:'post',
            data:param,
            success:function(res){
                if(res.data){
                    $(".dialog-wrap .export").attr("disabled",false);
                    that.initTable(res.data);
                }else{
                    $(".dialog-wrap .export").attr("disabled",true);
                    that.initTable([]);
                    layer.msg("暂无数据,请选择其他朝代或时间区间",{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    initTable:function(data){
        var that = this;
        layui.use('table', function(){
            var table = layui.table;
            table.render({
                elem: '#table'
                //,url: '/demo/table/user/' //数据接口
                ,data: data
                ,text: {
                    none: '暂无相关数据' //默认：无数据
                }
                ,cols: [[ //表头
                    {field: 'pclassname', title: '一级类目',minWidth:150}
                    ,{field: 'classname', title: '二级类目',minWidth:150}
                    ,{field: 'newy3', title: '朝代'}
                    ,{field: 'num', title: '次数'} 
                    ,{title: '记录内容',toolbar: '#barDemo',minWidth:80}
                    ]]
                ,page: false
                ,loading: true
            });  
            table.on('tool(test)', function(obj){
                var data = obj.data;
                if(obj.event === 'detail'){
                    that.getDetailDeep(data);
                }
            });
        });
        //that.total = data.entityCount;
    },
    getDetailDeep:function(data){
        var that = this;
        var param = {};
        param.newpid = data.newpid;
        param.newid = data.newid;
        param.l2 = data.l2;
        param.l3 = data.l3;
        param.y3 = data.newy3;
        param.startY1 = that.param.startY1;
        param.endY1 = that.param.endY1;
        //param.y3 = $("#dynasty").val();
        //that.detailParam = param;
        $.ajax({
            url:'/api/v1/meteorology/record/getRecords',
            type:'post',
            data:param,
            success:function(res){
                if(res.data){
                    //that.initBar(res.data);
                    that.layerIndex2 = layer.open({
                        type: 1,
                        title: "记录内容",
                        closeBtn: 1,
                        shadeClose:false,
                        content: template("content",res.data),
                        btn: ['关闭'],
                        area: ['800px', '500px']
                        ,yes: function(index, layero){
                          //按钮【按钮一】的回调
                          layer.close(that.layerIndex2);
                        },
                        success:function(){
                            
                        }
                    });
                }else{
                    //that.initBar(res.data);
                    //layer.msg("暂无数据,请选择其他朝代或时间区间",{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    getStationList:function(param){
        var that = this;
        $.ajax({
            url:'/api/v1/meteorology/record/list',
            type:'post',
            data:param,
            success:function(res){
                if(res.errcode == "0000"){
                    //that.renderTable(res.data)
                    that.points = res.data;
                    that.addPoints(res.data);
                }else{

                }
            },
            error:function(){

            }
        });
    }
}

app.init();